﻿using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.IO;

namespace TS2015.Areas.Admin.Controllers
{
    public class QuanTriTrangController : Controller
    {
        TS2015Context db = new TS2015Context();
        public ActionResult DanhSachTinTuc()
        {
            Database.SetInitializer<TS2015Context>(null);
            ViewBag.TheLoai = db.TbTheLoais.ToList();

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }

        public ActionResult TheLoaiTinTuc()
        {
            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }

        public IEnumerable<TbTinTuc> TinNoiBat()
        {
            return db.TbTinTucs.Where(e => e.NoiBat == true);
        }
        public IEnumerable<TbTinTuc> TinNoiBat(int SoLuongTin)
        {
            if (SoLuongTin > 0)            
                return db.TbTinTucs.Where(e => e.NoiBat == true).Take(SoLuongTin);

            return db.TbTinTucs.Where(e => e.NoiBat == true);
        }

        public ActionResult ThemHoacSuaTinTuc(string id)
        {
            TbTinTuc item = new TbTinTuc();
            SelectList LoaiTinTuc = null;
            if (ModelState.IsValid)
            {                          
                if (id != null)
                {
                    var idTT=long.Parse(id);
                    item = db.TbTinTucs.First(e => e.MaTinTuc == idTT);
                    LoaiTinTuc = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai", item.MaTheLoai);
                }
                else
                    LoaiTinTuc = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai");

                ViewBag.TheLoai = LoaiTinTuc;
            }

            if (!Request.IsAjaxRequest())
                return View(item);
      
            return PartialView(item);
        }

        [HttpPost]
        public ActionResult ThemHoacSuaTinTuc(TbTinTuc item)
        {
            if (item != null && ModelState.IsValid)
            {
                item.NgayDang = DateTime.Now;
                string fileName = "";

                var files = Request.Files["AnhDaiDien"];
                if (files != null && files.ContentLength > 0)
                    try
                    {                      
                        // Kiểm tra nếu trình duyệt IE thì cách lấy tên file khác
                        if (Request.Browser.Browser == "IE")
                            fileName = Path.GetFileName(files.FileName);
                        else
                            fileName = files.FileName;
                        // Đổi tên ảnh tránh bị mất file khi trùng tên.
                        fileName = (DateTime.Now.ToString("MMddyyyyHHmmssfff") + "_" + fileName);
                        string path = Path.Combine(Server.MapPath("~/Uploads/img"), fileName);
                        item.AnhDaiDien = fileName;
                        files.SaveAs(path);
                    }
                    catch (Exception ex)
                    {
                        ViewBag.Message = "Lỗi:" + ex.Message.ToString();
                    }

                //Nếu sửa tin tức
                if (item.MaTinTuc > 0)
                {
                    //Lấy ảnh đại diện cũ
                   string AnhDaiDien= db.TbTinTucs.AsNoTracking().First(e => e.MaTinTuc == item.MaTinTuc).AnhDaiDien;                                       

                    // Kiem tra co ảnh upload lên server ko
                   if (fileName!="" && AnhDaiDien != "")
                    {
                        // Xóa ảnh cũ
                        string fullPath = Request.MapPath("~/Uploads/img/" + AnhDaiDien);
                        if (System.IO.File.Exists(fullPath))
                            System.IO.File.Delete(fullPath);
                    }
                    else
                       item.AnhDaiDien = AnhDaiDien;
                    
                    db.Entry(item).State = EntityState.Modified;
                }
                // Thêm mới tin tức
                else
                    db.TbTinTucs.Add(item);
                // Lưu vào CSDL
                db.SaveChanges();
            }

            ViewBag.TheLoai = new SelectList(db.TbTheLoais.ToList(), "MaTheLoai", "TenTheLoai", item.MaTheLoai);
             

            TempData["Message"] = "Lưu thành công!";
            return RedirectToAction("DanhSachTinTuc");
            //if (!Request.IsAjaxRequest())
            //    return View(item);

            //return PartialView(item);
        }

        #region Thể loại tin tức
        public ActionResult Editing_ReadTheLoaiTT([DataSourceRequest] DataSourceRequest request)
        {
            var data = db.TbTheLoais;

            return Json(data.ToDataSourceResult(request));
        }

        public ActionResult Editing_CreateTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.TbTheLoais.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_UpdateTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_DestroyTheLoaiTT([DataSourceRequest] DataSourceRequest request, TbTheLoai data)
        {
            if (data != null)
            {
                TbTheLoai itemdata = db.TbTheLoais.First(item => item.MaTheLoai == data.MaTheLoai);
                db.TbTheLoais.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        #endregion

        #region Danh sách tin tức
        public ActionResult Editing_ReadTinTuc([DataSourceRequest] DataSourceRequest request)
        {
            var data = db.TbTinTucs;

            return Json(data.ToDataSourceResult(request));
        }

        public ActionResult Editing_CreateTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.TbTinTucs.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_UpdateTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult Editing_DestroyTinTuc([DataSourceRequest] DataSourceRequest request, TbTinTuc data)
        {
            if (data != null)
            {
                TbTinTuc itemdata = db.TbTinTucs.First(item => item.MaTinTuc == data.MaTinTuc);
                db.TbTinTucs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        #endregion
    }
}